package com.kfm.base.array2;

public class BinarySearch {

    public static void main(String[] args) {
        /*
            二分查找
                数组是一个已排序好的数组,否则不能保证结果
         */

        int[] arr = {1, 2, 3, 4, 5, 6};

        int num = 4;

        int left = 0;
        int right = arr.length - 1;
        int index = -1;

        while(left <= right){
            int middle = (left + right) >> 1;

            if (arr[middle] == num){
                index = middle;
                break;
            } else if(arr[middle] > num){
                right = middle - 1;
            } else {
                left = middle + 1;
            }
        }
        System.out.println(index);
    }
}
